package com.zgis.monitor.scheduler;

import com.zgis.monitor.config.MonitorConfig;
import com.zgis.monitor.model.ServiceStatus;
import com.zgis.monitor.service.MonitorService;
import com.zgis.monitor.util.MailUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 定时监控
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MonitorScheduler
{
    private final MonitorService monitorService;

    private final MonitorConfig monitorConfig;

    private final MailUtil mailUtil;

    private final List<MonitorConfig.ServerConfig> serverConfigs;

    // 定时检查服务状态
    @Scheduled(fixedRateString = "${monitor.check-rate:30000}", timeUnit = TimeUnit.SECONDS)
    public void checkAndRestartServices()
    {
        log.info("开始执行服务状态检查...");

        for (MonitorConfig.ServerConfig server : monitorConfig.getServers())
        {
            for (MonitorConfig.ServiceConfig service : server.getServices())
            {
                // 检查服务状态
                ServiceStatus status = monitorService.checkStatus(server, service);
                log.info("服务状态: {}@{} - {} - 运行中:{}",
                        status.getServiceId(), status.getServerIp(),
                        status.getServiceName(), status.isRunning());

                // 服务停止时，触发邮件告警+尝试自动重启
                if (!status.isRunning())
                {
                    //从当前服务配置中获取收件人
                    String recipients = service.getMailRecipients();

                    // 校验收件人配置
                    if (recipients == null || recipients.trim().isEmpty())
                    {
                        log.warn("服务 {}@{} 未配置邮件接收人，跳过告警发送", service.getId(), server.getIp());
                    }
                    else
                    {
                        // 发送告警邮件
                        mailUtil.sendServiceDownAlarm(recipients, server.getIp(), service);
                    }

                    boolean needRestart = service.getAutoRestart() != null ? service.getAutoRestart() : monitorConfig.isAutoRestart();
                    if (needRestart)
                    {
                        log.warn("服务 {}@{} 已停止，尝试自动重启...", service.getId(), server.getIp());
                        boolean restarted = monitorService.restartService(server, service);
                        if (restarted)
                        {
                            log.info("服务 {}@{} 重启成功", service.getId(), server.getIp());
                        }
                        else
                        {
                            log.error("服务 {}@{} 重启失败", service.getId(), server.getIp());
                        }
                    }
                }
            }
        }

        log.info("服务状态检查完成");
    }
}
    